package com.java.proxy;

import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Test {

    public static void main(String[] args) {
        // IUserDao userDao = new UserDaoImpl();


        //静态代理
        IUserDao userDao = new UserDaoProxy(new UserDaoImpl());
        userDao.save("张三");


        System.out.println("-----------------我是分割线----------------");

        //动态代理
        IUserDao userDao2 = (IUserDao) Proxy.newProxyInstance(IUserDao.class.getClassLoader(),
                new Class[]{IUserDao.class}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {


                        System.out.println("操作前的日志输出。。。。。。");

                        Object result = method.invoke(new UserDaoImpl(), args);

                        System.out.println("操作后的日志输出。。。。。。");

                        return result;
                    }
                });
        userDao2.save("李四");


        System.out.println();
        userDao2.query(1);

        //动态代理
        IUserDao userDao3 = (IUserDao) Proxy.newProxyInstance(IUserDao.class.getClassLoader(),
                new Class[]{IUserDao.class}, new UserDaoHandler());


        userDao3.save("李四");


        System.out.println();
        userDao3.query(1);


        //注：jdk动态代理的对象必须要有接口
        //代理类会继承Proxy对象
        //可查看TestGeneratorProxyClass.class文件查看
        byte[] bytes = ProxyGenerator.generateProxyClass("TestGeneratorProxyClass", new Class[]{IUserDao.class});

        try {
            FileOutputStream outputStream = new FileOutputStream(new File("TestGeneratorProxyClass.class"));
            outputStream.write(bytes);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
